import $kt from "../node-server-kantboot-util/index.js";
import net from 'net';
import axios from "axios";
import config from "../config.js";

let port = config.tcp.port;

// 客户端Map
let clientMap = new Map();

const server = net.createServer((socket) => {
    let clientKey = `${socket.remoteAddress}:${socket.remotePort}`;
    clientMap.set(clientKey, socket);
    console.log('客户端连接：', clientKey);

    socket.write(Buffer.from([1, 4, 1, 44, 0, 14, 177, 251]));

    // 获取客户端发送的数据
    socket.on('data', (data) => {
        let dataList = [];
        // data是hex类型的Buffer，需要转换成字符串
        for(let i=0;i<data.length;i++){
            dataList.push(data[i].toString(16));
        }
        console.log(dataList);

        let dateStr = $kt.date.format(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss');
        try{
            // 向中台告诉服务器，设备在线
            axios.post(`${config.middleground.url}/business-iot-web/api/iotDevice/heartbeat`, {sn: data.toString()});
        }catch (e) {

        }
    });

    // 监听socket关闭
    socket.on('close', (hadError) => {
        console.log('客户端关闭连接：', socket.remoteAddress + ":" + socket.remotePort);
    });

});

server.listen(port, () => {
    console.log(`TCP服务端口：${port}`);
});

export default server;